<template>
  <div class="container">
    <!--头部筛选 start-->
    <div class="flex-row justify-between p_b10">
      <div>
        <el-button size="small" type="primary" @click="onPageChange()">刷新</el-button>
      </div>
      <div>
        <el-button size="small" type="primary" @click="toggleEditorModal(true)" v-if="!isDoctor">新增留言</el-button>
      </div>
    </div>
    <!--头部筛选 end-->
    <div class="comments-content">
      <div class="item" v-for="(item,i) of tableData" :key="i">
        <div class="flex-row align-center head">
          <el-link href="javascript:;">
            @{{ doctorMap[item.doctorCode] || '医生' }}：
          </el-link>
        </div>
        <div class="">
          <el-image alt="" :src="item.cover" v-if="item.cover&&item.cover.trim().length"/>
        </div>
        <div class="p_y20 font14 text-black p_x10 comment">
          {{ item.content || '' }}
        </div>
        <div class="m_x25 m_y10 p_y10 line30 p_x5 doctor-reply flex-row">
          <span class="text-light">{{ doctorMap[item.doctorCode] || '医生' }} 回复：</span>
          <div class="flex1 flex-row justify-between" v-if="item.mmsReply">
            <span>{{ item.mmsReply.content }}</span>
            <el-button size="mini" type="danger" @click="onDeleteReply(item.mmsReply)" class="m_x10" v-if="isDoctor">
              删除回复
            </el-button>
          </div>
          <span class="text-light font14" v-else>暂未回复</span>

        </div>
        <div class="flex-row justify-between align-center font12 text-light foot">
          <div class="time">{{ format(item.createTime) }}</div>
          <div class="goods-info">
            <el-button size="small" @click="toggleEditorModal(true, item)" v-if="isDoctor">
              回复留言
            </el-button>
            <el-button size="small" @click="onDelete(item)" type="danger" v-else>
              删除留言
            </el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="row-align-center footer">
      <div class="text-light font12">---到底了---</div>
    </div>

    <!--分类编辑、新增弹框 start-->
    <el-dialog
        v-model="formData.show"
        :title="formData.data.questionCode&&formData.data.questionCode.length>0?'回复留言':'新增留言'"
        width="600px">
      <el-form
          ref="formRefName"
          :rules="rules"
          :model="formData.data" label-width="120px">
        <el-form-item label="选择医生" prop="doctorCode" v-if="!isDoctor">
          <el-select v-model="formData.data.doctorCode" placeholder="请选择医生">
            <el-option v-for="(item,i) of doctorData" :value="item.code" :label="item.name" :key="i"/>
          </el-select>
        </el-form-item>
        <el-form-item :label="formData.data.questionCode?'回复内容':'留言内容'" prop="content">
          <el-input
              type="textarea"
              :rows="5"
              v-model="formData.data.content" placeholder="留言内容" maxlength="200"
              show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="toggleEditorModal(false)">取消</el-button>
          <el-button size="small" type="primary" @click="onSubmit()">提交</el-button>
        </div>
      </template>
    </el-dialog>
    <!--分类编辑、新增弹框 end-->

  </div>


</template>

<script>
import {defineComponent, reactive, ref, toRaw, watch} from "vue"
import {deepClone, isEmpty} from "../../utils/helpers";
import Toast from "../../utils/Toast";
import Message from "../../api/modules/Message";
import {UploadFilled} from "@element-plus/icons-vue";
import {useStore} from "vuex";
import {RoleTypes} from "../../hooks/user/useUserLogin";
import Doctor from "../../api/modules/Doctor";
import dayjs from "dayjs";

export default defineComponent({
  name: "Message",
  components: {
    UploadFilled,
  },
  methods: {
    format(time, layout = 'YYYY-MM-DD HH:mm:ss') {
      return dayjs(time).format(layout)
    }
  },
  data() {
    return {
      // 表单路由验证规则 参考： https://element-plus.gitee.io/zh-CN/component/form.html#%E8%A1%A8%E5%8D%95%E6%A0%A1%E9%AA%8C
      rules: {
        doctorCode: [
          {required: true, message: "请选择医生"},
        ],
        content: [
          {required: true, message: "请填写留言内容"},
        ],

      },
    }
  },
  setup() {
    const store = useStore();
    const formRefName = ref(null);
    const params = reactive({
      filter: "",
    });
    const doctorData = ref([]); // 医生列表
    const doctorMap = ref({}); // 医生{code:name}
    const tableData = ref([]);// 留言列表


    getDoctorList(); //获取所有医生
    const isDoctor = ref(false); // 是否医生
    watch(() => store.state.user.role, val => {
      isDoctor.value = val === RoleTypes.doctor;
      // 监听到变化时请求一次（非医生角色获取到所有的医药分析，医生仅获取自己发布的内容）
      onPageChange(); // 初始化时直接请求一次分类列表
    }, {immediate: true});


    const formData = reactive({ // 新增编辑弹框的表单数据
      show: false, // 是否打开表单
      data: {
        doctorCode: '', // 医生编号
        patientCode: '', // 患者编号
        content: '', // 留言内容
      }
    });

    const _formData = deepClone(toRaw(formData)); // 拷贝一份原始的表单数据（用于还原数据使用）

    /**
     * 打开、关闭新增留言弹框
     * @param show true :打开 false 关闭
     * @param data
     */
    function toggleEditorModal(show, data = {}) {
      formData.show = show;
      formData.data = Object.assign(
          {}, // Object.assign 会填充到第一项的参数，使用一个{}空对象 防止数据污染
          _formData.data, // 备份的原始数据
          {
            doctorCode: data.doctorCode || '', // 医生code
            patientCode: data.patientCode || '', // 患者code
            questionCode: data.code || '', // 留言code
          }
      );
      if (formRefName.value) {
        formRefName.value.resetFields(); // 清除表单的验证信息
      }

    }

    // 新增、编辑提交
    function onSubmit() {
      if (!formRefName.value) {
        Toast.error('找不到表单')
        return;
      }
      formRefName.value.validate(async (valid) => {
        if (!valid) { // 表单验证不通过
          return;
        }
        // 拷贝一份表单数据
        const _formData = deepClone(toRaw(formData)).data;
        try {
          let res = {}
          if (!isEmpty(_formData.questionCode)) { // 医生回复留言
            res = await Message.doctorCreate(_formData)
          } else { // 患者留言
            delete _formData.questionCode;
            _formData.patientCode = store.state.user.userInfo.code;
            res = await Message.patientCreate(_formData);
          }
          onPageChange(); // 成功则刷新当前页面数据
          Toast.success(res.message || '操作成功');
          toggleEditorModal(false); //关闭新增、编辑弹框
        } catch (e) { // 新增、编辑操作提交错误或者失败
          Toast.error(e.message);
        }

      })
    }


    /**
     * 获取列表数据
     * @returns {Promise<void>}
     */
    async function onPageChange() {
      try {
        let res = {};
        const userCode = store.state.user.userInfo.code;
        if (isEmpty(userCode)) {
          return;
        }
        if (isDoctor.value) { // 医生
          res = await Message.doctorLists(userCode);
        } else {
          res = await Message.patientLists(userCode);
        }
        tableData.value = res.data || []; // 取到数据后直接覆盖旧的列表数据即可
      } catch (e) {
        console.log(e);
      }
    }

    /**
     * 获取所有医生列表数据
     * @returns {Promise<void>}
     */
    async function getDoctorList() {
      try {
        const {data} = await Doctor.lists({index: 1, limit: 99999});
        doctorData.value = (data.data || []).filter(v => v.role === 'doctor'); // 医生列表
        const _doctorMap = {};
        for (let item of doctorData.value) { // 将医生列表组装成[{code:name}]的形势
          _doctorMap[item.code] = item.name;
        }
        doctorMap.value = _doctorMap;
      } catch (e) {
        console.log(e);
      }
    }

    // 删除回复
    async function onDeleteReply(item) {
      try {
        const canDel = await Toast.confirm("确定删除回复吗?");
        if (!canDel) { // 取消删除操作
          return;
        }
        await Message.destroyReply(item.id)
        Toast.success("删除成功");
        onPageChange(); // 刷新列表
      } catch (e) { // 删除失败提示
        Toast.error(e.message);
      }
    }

    // 删除留言
    async function onDelete(item) {
      try {
        const canDel = await Toast.confirm("确定删除留言吗?");
        if (!canDel) { // 取消删除操作
          return;
        }
        await Message.destroy(item.id)
        Toast.success("删除成功");
        onPageChange(); // 刷新列表
      } catch (e) { // 删除失败提示
        Toast.error(e.message);
      }
    }

    return {
      onDelete,
      onDeleteReply,
      params,
      isDoctor,
      onSubmit,
      formData,
      doctorMap,
      doctorData,
      formRefName,
      toggleEditorModal,
      tableData,
      onPageChange,
    }
  },
})
</script>

<style lang="scss" scoped>
.comments-content {
  padding: 20px 0;


  .item {
    margin-bottom: 10px;
    padding: 10px;
    border-bottom: solid 1px #f8f8f8;

    &:last-child {
      border-width: 0;
    }

    .head {
      .cover {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        border-width: 0;
      }
    }

    .comment {
      margin-bottom: 10px;
      height: 58px;
      overflow: hidden;
    }

    .doctor-reply {
      background-color: #f9f9f9;
    }
  }
}
</style>
